<?php
//正式部署删掉下面这行
throw new MyException('not impletment',MyException::THIRD);
/**
 * @exception 400 参数错误
 * @exception 502 服务器错误
 * @exception 503 数据库错误
 */
class UnionController extends CI_Controller
{
    //sdk配置文件位置
    const PATH=__DIR__.'/../config/oauth.php';

    /**
     * 非通用框架需要在构造函数调用此函数
     */
    protected function _auth()
    {
        if (is_cli()) return;
        $time=isset($_SERVER['HTTP_TIME'])?$_SERVER['HTTP_TIME']:0;
        $token=isset($_SERVER['HTTP_TOKEN'])?$_SERVER['HTTP_TOKEN']:'';
        if (time()-$time>60) show_404();
        if (md5(md5($time).'fff')!=$token) show_404();
    }

    /**
     * 服务器推送更新组织信息
     */
    function department()
    {
        $data=$this->input->post('data');
        $data=json_decode($data,true);
        if ($data){
            $this->_updateDept($data);
        }
    }
    /**
     * 初始化配置
     * 根据实际情况修改保存的配置文件类型
     */
    function config()
    {
        $data=$this->input->post();
        $write=['<?php'];
        foreach ($data as $key => $value) {
            if (!ctype_alnum($key)) throw new MyException('',MyException::INPUT_ERR);
            if (!ctype_alnum($value)){
                if (($key!='host' && $key!='entry' ) || strpos($value,"'") !==false) throw new MyException('',MyException::INPUT_ERR);
            }
            $write[]="\$config['$key']='$value';";
        }
        file_put_contents(self::PATH,implode(PHP_EOL,$write));
        restful();
    }

   /**
    * 通过cli主动拉取配置信息
    */
    function updateDept()
    {
        $this->load->library('oauth');
        $data=$this->oauth->department();
        $this->_updateDept($data);
    }

   /**
    * 其他平台退出，此平台也要退出
    */
    function logout()
    {
        $openid=$this->input->get('openid');
        $this->db->where('openid',$openid)->update('user',['token'=>uniqid()]);
        restful();
    }

    function _updateDept($data)
    {
        $ori=$this->db->order_by('id','asc')->get('department')->result_array();
        reset($ori);
        $p=current($ori);
        foreach ($data as $value) {
            if (!$p){
                //后面都是新加的数据了
                $this->db->insert('department',$value);
                continue;
            }
            if ($value['id']==$p['id']){
                $this->db->where('id',$p['id'])->update('department',$value);
                $p=next($ori);
            }else{
                while ($p && $value['id']>$p['id']) {
                    $p=next($ori);
                }
                if ($value['id']<=$p['id']){
                    //源站在中间直接插入了一条数据，加上
                    $this->db->insert('department',$value);
                }
                if ($value['id']==$p['id']){
                    $p=next($ori);
                }
            }
        }
    }
}